package com.yuanhua.sim.netty.serve.handler;

import com.yuanhua.auth.server.utils.JwtTokenServerUtils;
import com.yuanhua.core.base.entity.LoginReqBean;
import com.yuanhua.core.base.entity.LoginResBean;
import com.yuanhua.core.utils.SpringUtils;
import com.yuanhua.sim.netty.utils.NettyAttrUtil;
import com.yuanhua.sim.netty.utils.SessionUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * * @description TODO
 * * @author songguoxiang@yunquna.com
 * * @date 2024/03/29 17:15
 */
@Slf4j
public class LoginReqHandler extends SimpleChannelInboundHandler<LoginReqBean> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginReqBean loginReqBean) throws Exception {
        NettyAttrUtil.updateReaderTime(channelHandlerContext.channel(), System.currentTimeMillis());
        //1.登录请求
        log.info("客户端登录：{}", loginReqBean.toString());
        login(loginReqBean,channelHandlerContext.channel());
    }

    /**
     * 登录方法
     * @param bean 登录实体
     * @param channel
     */
    private void login(LoginReqBean bean, Channel channel){
        LoginResBean res=new LoginResBean();
        //根据用户token进行解析；解析成功则认证通过
        JwtTokenServerUtils jwtTokenServerUtils = SpringUtils.getBean(JwtTokenServerUtils.class);

        String userInfo;
        try {
            //jwtTokenServerUtils.getUserInfo(bean.getUsername());
        } catch (RuntimeException e) {
            e.printStackTrace();
            log.info("非法用户，无法登录");
            //通道不为空，证明该用户已经在线了
            res.setStatus(0);
            res.setMsg("用户过期");
            channel.writeAndFlush(res);
            throw new RuntimeException(e.getMessage());
        }

        //从map里面根据用户ID获取连接通道
        Channel c= SessionUtils.getChannel(bean.getUserid());;
        if(c==null){
            //通道为空，证明该用户没有在线
            //1.添加到map
            SessionUtils.userIdChannelMap.put(bean.getUserid(), channel);
            //2.给通道赋值
            channel.attr(AttributeKey.valueOf("userid")).set(bean.getUserid());
            //保存关系到redis :
            //3.响应
            res.setStatus(0);
            res.setMsg("登录成功");
            res.setUserid(bean.getUserid());
            channel.writeAndFlush(res);
        }else{
            //通道不为空，证明该用户已经在线了
            res.setStatus(1);
            res.setUserid(bean.getUserid());
            res.setMsg("该账户目前在线");
            channel.writeAndFlush(res);
        }
    }
}
